﻿<?php
require_once '../../library/config.php'; 
require_once '../library/functions.php';

checkUser();

$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
	
    case 'add' :
        addChude();
        break;
      
    case 'modify' :
        modifyChude();
        break;
        
    case 'delete' :
        deleteChude();
        break;
    
	   
    default :
        // if action is not defined or unknown
        // move to main Chude page
        header('Location: index.php');
}


/*
    Add a Chude
*/
function addChude()
{
    $ten       = $_POST['txtName'];
    $noidung = $_POST['mtxDescription'];    
    $sql   = "INSERT INTO tbl_chude (Chude) 
              VALUES ('$ten')";
    $result = dbQuery($sql) or die('Cannot add Chude' . mysql_error());
    
    header('Location: index.php?chudeId=' . $chudeId);              
}

/*
    Upload an image and return the uploaded image name 
    Modify a Chude
*/
function modifyChude()
{
    $chudeId       = (int)$_GET['chudeId'];
    $ten        = $_POST['txtName'];
    
    // if uploading a new image
    // remove old imag     
    $sql    = "UPDATE tbl_chude 
               SET Chude = '$ten'
               WHERE Chude_id = $chudeId";
           
    $result = dbQuery($sql) or die('Cannot update Chude. ' . mysql_error());
    header('Location: index.php');              
}

/*
    Remove a Chude
*/
function deleteChude()
{
    if (isset($_GET['chudeId']) && (int)$_GET['chudeId'] > 0) {
        $chudeId = (int)$_GET['chudeId'];
    } else {
        header('Location: index.php');
    }
    
	// find all the children categories
	
	// make an array containing this Chude and all it's children
	$chude  = array_merge(array($chudeId));
	$numChude = count($chude);

	// remove all product image & thumbnail 
	// if the product's Chude is in  $chude
	$sql = "SELECT Tintuc_id, Image
	        FROM tbl_tintuc
			WHERE Chude_id IN (" . implode(',', $chude) . ")";
	$result = dbQuery($sql);
	
	while ($row = dbFetchAssoc($result)) {
		@unlink(SRV_ROOT . TINTUC_IMAGE_DIR . $row['Image']);	
		//@unlink(SRV_ROOT . PRODUCT_IMAGE_DIR . $row['pd_thumbnail']);
	}
	
	// delete the products
	$sql = "DELETE FROM tbl_tintuc
			WHERE Chude_id IN (" . implode(',', $chude) . ")";
	$result=dbQuery($sql);

    // finally remove the Chude from database;
    $sql = "DELETE FROM tbl_chude 
            WHERE Chude_id IN (" . implode(',', $chude) . ")";
    dbQuery($sql);
    
    header('Location: index.php');
}


/*
	Recursively find all children of $chudeId
*/


/*
    Remove a Chude image
*/

/*
	Delete a Chude image where Chude = $chudeId
*/
?>